package com.handpay.nocardpay.baselibrary.qualificationinfo.view.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.NoCardPayApplication;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.location.LocationService;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.permission.PermissionRequest;
import com.handpay.nocardpay.baselibrary.permission.PermissionCode;
import com.handpay.nocardpay.baselibrary.qualificationinfo.comm.CommonHelper;
import com.handpay.nocardpay.baselibrary.qualificationinfo.model.bean.BundleBean;
import com.handpay.nocardpay.baselibrary.qualificationinfo.presenter.QualificationPresenterImpl;
import com.handpay.nocardpay.baselibrary.qualificationinfo.view.IQualificationPictureView;
import com.handpay.nocardpay.baselibrary.qualificationinfo.widgets.QualificationPhotoView;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.MyAsyncTask;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.HashMap;
import java.util.List;

/**
 * Created by fplei on 2017/8/13.
 * 资质信息--图片信息
 */

public class QualificationPictureInfoFragment extends BaseFragment implements IQualificationPictureView {
    private Toolbar mToolbar;
    private QualificationPhotoView c_id_front_photo, c_id_back_photo, c_id_hold_photo;
    private QualificationPhotoView c_id_shop_photo, c_id_business_licence_photo;
    private LinearLayout reupload_warning;
    private TextView reupload_warning_content;
    private Uri mPicUri;
    public static int TAKE_PICTURE = 1;

    public static int TAKE_PICTURE_FRONT = TAKE_PICTURE + 1;
    public static int TAKE_PICTURE_BLACK = TAKE_PICTURE + 2;
    public static int TAKE_PICTURE_IN_HAND = TAKE_PICTURE + 3;
    public static int TAKE_PICTURE_SHOP = TAKE_PICTURE + 4;
    public static int TAKE_PICTURE_BUSINESS_LICENCE = TAKE_PICTURE + 5;
    private int CurrentRequestCode = 0;
    private volatile boolean mFrontUploaded = false;
    private volatile boolean mBackUploaded = false;
    private volatile boolean mInHandUploaded = false;
    private Button nextButton;
    //data from QualificationBaseInfoFragment
    private BundleBean bundleBean = null;
    ProgressDialog progressDialog = null;
    private QualificationPresenterImpl qualificationPresenter;
    private MyAsyncTask<Void, BaseProtocolKey.TYPE, Integer> mTask;

    private QualificationPhotoView.UploadClickListener mUploadClickListener = null;
    private PermissionRequest permissonRequest;
    private String[] permissons = Permission.CAMERA;
    private String[] permissonsLocation = Permission.LOCATION;
    private PermissionListener permissionListener;
    private LocationService locationService;

    public static QualificationPictureInfoFragment newInstance(Bundle args) {
        QualificationPictureInfoFragment fragment = new QualificationPictureInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.qualification);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_qualification_pictureinfo;
    }

    @Override
    public void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(mToolbar, true);
        reupload_warning = (LinearLayout) view.findViewById(R.id.reupload_warning);
        reupload_warning_content = (TextView) view.findViewById(R.id.reupload_warning_content);
        c_id_front_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_front_photo);
        c_id_back_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_back_photo);
        c_id_hold_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_hold_photo);

        c_id_shop_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_shop_photo);
        c_id_business_licence_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_business_licence_photo);
        nextButton = (Button) view.findViewById(R.id.nextButton);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        permissonRequest = new PermissionRequest(_mActivity);
        qualificationPresenter = new QualificationPresenterImpl(_mActivity, this);
        bundleBean = (BundleBean) getArguments().getParcelable(BaseProtocolKey.KEY_BASEINFO);
        HPLog.i(HPLog.LFP_TAG, "QualificationPictureInfoFragment::initData:bundleBean=" + (bundleBean != null ? bundleBean.toString() : ""));
        if (AccountUtils.AccountStatus.FAIL == AccountUtils.getAccountStatus(_mActivity)) {
            reupload_warning.setVisibility(View.VISIBLE);
            reupload_warning_content.setText(AccountUtils.getAccountFailDes(_mActivity));
        } else {
            reupload_warning.setVisibility(View.GONE);
        }
//        bundleBean=new BundleBean();
//        bundleBean.setFrontCCPic("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4267222417,1017407570&fm=200&gp=0.jpg");
//        bundleBean.setFrontCCPicStatus("1");
//        bundleBean.setBackCCPic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502857653662&di=c66d59287d0a3db945562e813dcecb70&imgtype=0&src=http%3A%2F%2Fimg06.tooopen.com%2Fimages%2F20160712%2Ftooopen_sy_170083325566.jpg");
//        bundleBean.setBackCCPicStatus("0");
//        bundleBean.setHoldPic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502857653662&di=46d6303ed06d04df6be04d6d2cedb5e7&imgtype=0&src=http%3A%2F%2Fpic49.nipic.com%2Ffile%2F20140927%2F19617624_230415502002_2.jpg");
//        bundleBean.setHoldPicStatus("1");
        String temp_front_url = "";
        int temp_front_status = -1;
        String temp_back_url = "";
        int temp_back_status = -1;
        String temp_hold_url = "";
        int temp_hold_status = -1;
        if (bundleBean != null) {
            temp_front_url = bundleBean.getFrontCCPic();
            temp_front_status = CommonUtils.objectToInt(bundleBean.getFrontCCPicStatus());
            temp_back_url = bundleBean.getBackCCPic();
            temp_back_status = CommonUtils.objectToInt(bundleBean.getBackCCPicStatus());
            temp_hold_url = bundleBean.getHoldPic();
            temp_hold_status = CommonUtils.objectToInt(bundleBean.getHoldPicStatus());
        }
        c_id_front_photo.initData(R.drawable.qualification_cardfront_hint, temp_front_url, temp_front_status, mUploadClickListener);
        c_id_back_photo.initData(R.drawable.qualification_back_hint, temp_back_url, temp_back_status, mUploadClickListener);
        c_id_hold_photo.initData(R.drawable.qualification_holdandcard_hint, temp_hold_url, temp_hold_status, mUploadClickListener);
        c_id_shop_photo.initData(R.drawable.qualification_shop_hint, "", -1, mUploadClickListener);
        c_id_business_licence_photo.initData(R.drawable.qualification_business_licence_hint, "", -1, mUploadClickListener);

        //location service
        locationService = ((NoCardPayApplication) _mActivity.getApplication()).locationService;
        locationService.registerListener();

        //permission callback
        permissionListener = new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                switch (requestCode) {
                    case PermissionCode.LOCATION_PERMISSION_CODE:
                        submmitData();
                        break;
                    case PermissionCode.CAMERA_PERMISSION_CODE:
                        openCamera();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
                if (AndPermission.hasAlwaysDeniedPermission(_mActivity, deniedPermissions)) {
                    // 第一种：用默认的提示语。
                    AndPermission.defaultSettingDialog(QualificationPictureInfoFragment.this, PermissionCode.REQUEST_CODE_SETTING).show();
                }
            }
        };
    }

    @Override
    public void initListener() {
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissonRequest.requestPermission(PermissionCode.LOCATION_PERMISSION_CODE, permissionListener, permissonsLocation);
            }
        });
        mUploadClickListener = new QualificationPhotoView.UploadClickListener() {
            @Override
            public void onUploadClickListener(QualificationPhotoView view) {
                CurrentRequestCode = TAKE_PICTURE;
                if (c_id_front_photo == view) {
                    CurrentRequestCode = TAKE_PICTURE_FRONT;
                } else if (c_id_back_photo == view) {
                    CurrentRequestCode = TAKE_PICTURE_BLACK;
                } else if (c_id_hold_photo == view) {
                    CurrentRequestCode = TAKE_PICTURE_IN_HAND;
                } else if (c_id_shop_photo == view) {
                    CurrentRequestCode = TAKE_PICTURE_SHOP;
                } else if (c_id_business_licence_photo == view) {
                    CurrentRequestCode = TAKE_PICTURE_BUSINESS_LICENCE;
                }
                permissonRequest.requestPermission(PermissionCode.CAMERA_PERMISSION_CODE, permissionListener, permissons);
            }

            @Override
            public void checkBigPitcure(String uri) {
                String temp_uri = uri;
                start(BigPictureFragment.newInstance(temp_uri));
            }
        };
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mPicUri = CommonUtils.randomUri(CommonUtils.getAccessDir());
        HPLog.i(HPLog.LFP_TAG, "mPicUri:" + mPicUri.toString());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicUri);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CurrentRequestCode);
    }

    /**
     * 上传文件
     */
    private void submmitData() {
        String message = "";
        String frontUri = c_id_front_photo.getPicUri();
        String backUri = c_id_back_photo.getPicUri();
        String inHandUri = c_id_hold_photo.getPicUri();
        if (TextUtils.isEmpty(frontUri) || !c_id_front_photo.isLoadSuccess) {
            message = getString(R.string.tv_please_takephoto_front);
        } else if (TextUtils.isEmpty(backUri) || !c_id_back_photo.isLoadSuccess) {
            message = getString(R.string.tv_please_takephoto_back);
        } else if (TextUtils.isEmpty(inHandUri) || !c_id_hold_photo.isLoadSuccess) {
            message = getString(R.string.tv_please_takephoto_hold);
        }
        if (!TextUtils.isEmpty(message)) {
            DialogUtils.showToast(_mActivity, message);
            return;
        }
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        HPLog.i(HPLog.LFP_TAG, "--address:" + address);
        if (!TextUtils.isEmpty(address)) {
            doUpload();
        } else {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.message_alert_no_found_gps), false, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    locationService.start();
                    dialog.dismiss();
                }
            });
            return;
        }
    }

    private void doUpload() {
        HPLog.i("time", "doUpload:" + SystemClock.elapsedRealtime());
        cancelTask();
        //分别上传四、五张照片。最后发送提交.如果其中有一个发送失败。提示用户发送失败，请重新提交。
        //返回值。0表示成功，1表示失败，2，表示用户取消
        mTask = new MyAsyncTask<Void, BaseProtocolKey.TYPE, Integer>() {
            @Override
            protected void onPreExecute() {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onPreExecute");
                progressDialog = new ProgressDialog(_mActivity);
                progressDialog.setMessage(getString(R.string.uploading_template, ""));//
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(false);
                progressDialog.show();
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Integer result) {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onPostExecute");
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                if (CommonHelper.UPLOAD_SUCCESS == result) {
                    //成功以后，删除图片
                    CommonUtils.removePics();
                    gotoUploadSuccess();
                } else if (CommonHelper.UPLOAD_FAIL == result) {
                    //上传失败
                    DialogUtils.showToast(_mActivity, getString(R.string.upload_failed));
                } else if (CommonHelper.UPLOAD_CANCEL == result) {
                    //上传取消
                    DialogUtils.showToast(_mActivity, getString(R.string.upload_cancel));
                }
                super.onPostExecute(result);
            }

            @Override
            protected void onProgressUpdate(BaseProtocolKey.TYPE... values) {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onProgressUpdate.values=" + values.toString());
                if (null != progressDialog) {
                    String picDes = CommonHelper.getPicDesWithPicType(_mActivity, values[0]);
                    progressDialog.setMessage(getString(R.string.uploading_template, picDes));
                }
                super.onProgressUpdate(values);
            }

            @Override
            protected void onCancelled(Integer result) {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onCancelled");
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                //上传取消
                DialogUtils.showToast(_mActivity, getString(R.string.upload_cancel));
                super.onCancelled();
            }

            @Override
            protected Integer doInBackground(Void... params) {
                //发送正面图片
                if (!mFrontUploaded) {
                    if (startUpload(c_id_front_photo.getPicUri(), BaseProtocolKey.TYPE.FRONT)) {
                        this.publishProgress(BaseProtocolKey.TYPE.FRONT);
                        mFrontUploaded = true;
                    } else {
                        return CommonHelper.UPLOAD_FAIL;
                    }
                }
                if (this.isCancelled()) {
                    return CommonHelper.UPLOAD_CANCEL;
                }
                //发送反面图片
                if (!mBackUploaded) {
                    if (startUpload(c_id_back_photo.getPicUri(), BaseProtocolKey.TYPE.BACK)) {
                        this.publishProgress(BaseProtocolKey.TYPE.BACK);
                        mBackUploaded = true;
                    } else {
                        return CommonHelper.UPLOAD_FAIL;
                    }
                }
                if (this.isCancelled()) {
                    return CommonHelper.UPLOAD_CANCEL;
                }
                //发送手持图片
                if (!mInHandUploaded) {
                    if (startUpload(c_id_hold_photo.getPicUri(), BaseProtocolKey.TYPE.INHAND)) {
                        this.publishProgress(BaseProtocolKey.TYPE.INHAND);
                        mInHandUploaded = true;
                    } else {
                        return CommonHelper.UPLOAD_FAIL;
                    }
                }
                if (this.isCancelled()) {
                    return CommonHelper.UPLOAD_CANCEL;
                }
                return CommonHelper.UPLOAD_SUCCESS;
            }
        };
        mTask.execute();
    }

    private void cancelTask() {
        //当该activity不可见的时候，取消上传任务。
        if (null != mTask) {
            HPLog.i("ssss", "cancel task");
            mTask.cancel(true);
            mTask = null;
        }
    }

    /**
     * 开始上传图
     *
     * @param uri
     * @param type
     * @return
     */
    private boolean startUpload(String uri, BaseProtocolKey.TYPE type) {

        return CommonHelper.uploadPhotoJson(_mActivity, qualificationPresenter, uri, type, CommonHelper.UploadModel.QUALIFICATION_UPLOADPICTURE);
    }

    /**
     * 上传资质信息
     */
    private void gotoUploadSuccess() {
        HPLog.i(HPLog.LFP_TAG, "QualificationPictureInfoFragment::gotoUploadSuccess::starParams=" + bundleBean.toString());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put(BaseProtocolKey.NAME, SecureManager.getInstance().des(bundleBean.getName(), 1, null));
        params.put(BaseProtocolKey.CERTNO, SecureManager.getInstance().des(bundleBean.getCertNo(), 1, null));
        params.put(BaseProtocolKey.RECOMMENDER, SecureManager.getInstance().des(bundleBean.getShareCode(), 1, null));
        params.put(BaseProtocolKey.CARDNO, SecureManager.getInstance().des(bundleBean.getCardNo(), 1, null));
        params.put(BaseProtocolKey.BANKCODE, bundleBean.getBankCode());
        if (!TextUtils.isEmpty(bundleBean.getSubBankCode())) {
            params.put(BaseProtocolKey.SUBBANKCODE, bundleBean.getSubBankCode());
        }
        appendAddresses(params, true);
        params.put(BaseProtocolKey.CLIENTCHANNEL, NoCardPayConfig.CLIENTCHANNEL);
        params.put(BaseProtocolKey.CHANNEL, NoCardPayConfig.CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, "1");
        //如果是重新提交的type传2
        if ((!TextUtils.isEmpty(bundleBean.getFrontCCPic()) && bundleBean.getFrontCCPic().startsWith("http"))
                || (!TextUtils.isEmpty(bundleBean.getBackCCPic()) && bundleBean.getBackCCPic().startsWith("http")) || (!TextUtils.isEmpty(bundleBean.getHoldPic()) && bundleBean.getHoldPic().startsWith("http"))) {
            params.put(BaseProtocolKey.KEY_TYPE, "2");
        } else {
            params.put(BaseProtocolKey.KEY_TYPE, "1");
        }
        HPLog.i(HPLog.LFP_TAG, "QualificationPictureInfoFragment::gotoUploadSuccess::params:" + params.toString());
        qualificationPresenter.submitData(params, true);
    }

    public void appendAddresses(HashMap<String, Object> p, boolean isLocation) {
        String lat = BaseProtocolKey.KEY_LATITUDE;
        String loat = BaseProtocolKey.KEY_LONGTITUDE;
        String adds = BaseProtocolKey.KEY_ADDRESS;
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(lat, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(loat, 0d);
        String add = (String) ClientEngine.getInstance().getGlobal(adds);
        if (0d != latitude && 0d != longtitude && !TextUtils.isEmpty(add)) {
            if (isLocation) {
                p.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
                p.put(BaseProtocolKey.KEY_ADDRESS, add);
            }
        } else {
            HPLog.e(HPLog.YL_TAG, "no address!");
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        HPLog.i(HPLog.LFP_TAG, "QualificationPictureInfoFragment::onActivityResult::resultCode=" + resultCode);
        if (Activity.RESULT_OK == resultCode) {
            QualificationPhotoView photo = null;
            if (TAKE_PICTURE_FRONT == requestCode) {
                photo = c_id_front_photo;
            } else if (TAKE_PICTURE_BLACK == requestCode) {
                photo = c_id_back_photo;
            } else if (TAKE_PICTURE_IN_HAND == requestCode) {
                photo = c_id_hold_photo;
            } else if (TAKE_PICTURE_SHOP == requestCode) {
                photo = c_id_shop_photo;
            } else if (TAKE_PICTURE_BUSINESS_LICENCE == requestCode) {
                photo = c_id_business_licence_photo;
            }
            if (mPicUri != null) {
                String uri = mPicUri.toString();
                HPLog.i(HPLog.LFP_TAG, "onActivityResult::uri=" + uri);
                photo.setPic(uri);
            }
            mPicUri = null;
        } else if (Activity.RESULT_CANCELED == resultCode) {
            //取消
        }
    }

    @Override
    public void submmitQualificationSuccess() {
        HPLog.i(HPLog.LFP_TAG, "----submmitQualificationSuccess----");
        DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.qualification_submit_success_tip));
        startWithPop(QualificationSuccessFragment.newInstance());
    }

    @Override
    public void submmitQualificationFail(String errorMesg) {
        HPLog.i(HPLog.LFP_TAG, "submmitQualificationFail");
        DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), errorMesg, false, getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideSoftInput();
    }

    @Override
    public void onDestroy() {
        locationService.unregisterListener();
        locationService.stop();
        qualificationPresenter.onDestory();
        super.onDestroy();
    }


}
